import React from 'react';
import moment from 'moment';
import CalendarSelect from './CalendarSelect';
import DaySchedule from './DaySchedule';
import { checkIntersection, px2Time, formatStaticMap, formatHM } from './utils';
import styles from './index.less';

const DATE_FORMAT = 'YYYY-MM-DD';

const ROWS_NUM = 48;
const ROW_HEIGHT = 22;
const MIN_UNIT = 22;

const getTotalCount = obj => {
    if (!obj) return 0;
    const arr = Object.values(obj);
    return arr?.reduce((prev, cur) => prev + cur?.length || 0, 0);
};

const getSelectedList = obj => {
    if (!obj) return [];
    const arr = Object.keys(obj);
    return arr?.reduce((prev, cur) => {
        if (obj?.[cur]?.length > 0) {
            return prev.concat(cur);
        }
        return prev;
    }, []);
};

const currentTimeItem = text => (
    <div style={{ height: 1, backgroundColor: 'red' }}>
        <div
            style={{
                position: 'absolute',
                width: 5,
                height: 5,
                borderRadius: '50%',
                top: 0,
                left: 0,
                transform: 'translateY(-50%)',
                backgroundColor: 'red'
            }}
        />
        <div
            style={{
                position: 'absolute',
                color: 'red',
                left: 0,
                fontSize: 12,
                transform: 'translate(-100%, -50%)',
                textAlign: 'centner',
                width: 57,
                pointerEvents: 'none'
            }}
        >
            {text}
        </div>
    </div>
);

const getCustomItems = currentTime => [
    {
        id: 1,
        range: [formatHM(currentTime, MIN_UNIT), formatHM(currentTime.add(4, 'm'), MIN_UNIT)],
        render: currentTimeItem(currentTime.format('HH:mm'))
    }
];

const CalendarMobile = React.forwardRef(({ staticRangeMap, onSelectChange }, ref) => {
    const [dateTimeObj, setDateTimeObj] = React.useState(null);
    const rows = [...Array(24).keys()];
    const [nowDate, setNowDate] = React.useState(moment().format(DATE_FORMAT));
    const [tip, setTip] = React.useState({ first: true, show: true });

    const staticObj = React.useMemo(() => formatStaticMap(staticRangeMap, MIN_UNIT), [JSON.stringify(staticRangeMap)]);

    const customItems = getCustomItems(moment()); // 自定义的附加数据，这里是显示当前时间

    React.useImperativeHandle(ref, () => ({
        submit: () => {
            if (!dateTimeObj) return [true];
            const arr = Object.keys(dateTimeObj);
            if (arr.length === 0) return [true];
            let flag = false;
            const finalArr = [];
            arr.forEach(item => {
                const range = dateTimeObj[item] || [];
                const staticRange = staticObj[item] || [];
                range.forEach(it => {
                    finalArr.push({
                        startTime: `${item} ${px2Time(it.range[0], MIN_UNIT)}:00`,
                        endTime: `${item} ${px2Time(it.range[1], MIN_UNIT)}:00`
                    });
                    if (staticRange.some(it2 => checkIntersection(it2.range, it.range))) {
                        flag = true;
                    }
                });
            });
            return [flag, finalArr];
        }
    }));

    const handleScheduleChange = o => {
        setDateTimeObj({
            ...dateTimeObj,
            ...o
        });
    };

    React.useEffect(() => {
        const cnt = getTotalCount(dateTimeObj);
        onSelectChange(cnt > 0);
    }, [dateTimeObj]);

    return (
        <div className={styles.calendarContainerMobile}>
            <div className={styles.calendarTitle}>
                <div>{nowDate ? moment(nowDate).format('YYYY年M月') : ''}</div>
                <div style={{ fontSize: 14 }}>已选{getTotalCount(dateTimeObj)}</div>
            </div>
            <CalendarSelect
                value={nowDate}
                defaultSelectedList={getSelectedList(dateTimeObj)}
                onChange={d => setNowDate(d)}
            />
            <div className={styles.mainSchedule}>
                <div className={styles.hourSchedule}>
                    <span
                        style={{
                            position: 'absolute',
                            top: 2,
                            left: '50%',
                            transform: 'translateX(-50%)'
                        }}
                    >
                        00:00
                    </span>
                    {rows.map(rowIndex => (
                        <div key={rowIndex} className={styles.hourHeadItem}>
                            <span
                                style={{
                                    position: 'absolute',
                                    bottom: -10,
                                    left: '50%',
                                    transform: 'translateX(-50%)'
                                }}
                            >
                                {rowIndex + 1 < 10 ? '0' : ''}
                                {rowIndex + 1}:00
                            </span>
                        </div>
                    ))}
                </div>

                <div className={styles.hourScheduleItem}>
                    <DaySchedule
                        key={nowDate}
                        date={nowDate}
                        defaultRangeList={dateTimeObj?.[nowDate] || []}
                        onChange={handleScheduleChange}
                        rowsNum={ROWS_NUM}
                        rowHeight={ROW_HEIGHT}
                        minUnit={MIN_UNIT}
                        staticRangeList={staticObj?.[nowDate] || []}
                        tip={tip}
                        setTip={setTip}
                        customItems={customItems}
                    />
                </div>
            </div>
        </div>
    );
});

export default CalendarMobile;
